<template>
  <div class="header wrapper">
    <div class="head-search">
      <div class="head-inner">
        <div class="logo">
          <div class="img-box">
            <a href="#"><img src="../../assets/images/wp.png" alt=""></a>
          </div>
        </div>
        <div class="service">
          <span class="zp">
            <img src="../../assets/images/image.png" alt="">
          </span>
        </div>

        <div class="shop-box">
          <div class="shop-wrap">
            <a href="#/cart">
              <svg xmlns="http://www.w3.org/2000/svg" width="20px" height="20px" viewBox="0 0 24 10">
                <g fill="none" stroke="currentColor" stroke-width="1.5">
                  <path stroke-linecap="round"
                    d="m2 3l.265.088c1.32.44 1.98.66 2.357 1.184S5 5.492 5 6.883V9.5c0 2.828 0 4.243.879 5.121c.878.879 2.293.879 5.121.879h8" />
                  <path
                    d="M7.5 18a1.5 1.5 0 1 1 0 3a1.5 1.5 0 0 1 0-3Zm9 0a1.5 1.5 0 1 1 0 3a1.5 1.5 0 0 1 0-3Z"
                    opacity=".5" />
                  <path
                    d="M5 6h11.45c2.055 0 3.083 0 3.528.674c.444.675.04 1.619-.77 3.508l-.429 1c-.378.882-.567 1.322-.942 1.57c-.376.248-.856.248-1.815.248H5" />
                </g>
              </svg>
              <span>购物袋</span>
              <span class="num">{{ cartItemCount }}</span>
            </a>
          </div>
        </div>

        <div class="search-inner">
          <div class="input-from">
            <input type="text" v-model="searchQuery" @input="searchProducts" @focus="showResults = true"
              @blur="hideResults" placeholder="搜索产品">
            <button class="button">
              <!-- 这里可以放搜索图标 -->
            </button>
          </div>
          <div class="search-results" v-if="showResults && searchResults.length > 0"
            @mouseenter="pauseAutoHide" @mouseleave="resumeAutoHide">
            <div class="results-container">
              <ul>
                <li v-for="(item, index) in uniqueSearchResults" :key="item.id" @click="goToDetail(item.id)"
                  @mouseenter="highlightItem(index)"
                  :class="{ highlighted: highlightedIndex === index }">
                  <div class="product-info">
                    <span class="product-name">{{ item.name }}</span>
                    <span class="product-price">¥{{ formatPrice(item.price) }}</span>
                  </div>
                </li>
              </ul>
            </div>
          </div>
        </div>
      </div>
    </div>
    
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import axios from 'axios'
import { useRouter } from 'vue-router';
 
export default {
  name: 'HeaderNav',
  props: {
    type: {
      type: String,
      required: false
    }
  },
  setup(props, { emit }) {
    const router = useRouter();
    const cartList = ref([]);
    const cartItemCount = ref(0);
    const searchQuery = ref('');
    const searchResults = ref([]);
    const showResults = ref(false);
    const highlightedIndex = ref(-1);
    const autoHideTimer = ref(null);
    const activeNavIndex = ref(0); // 默认选中第一个导航项
    let intervalId = null;
 
    // 导航项配置
    const navItems = ref([
      { label: '推荐', type: '小编推荐' },
      { label: '卫衣', type: '卫衣' },
      { label: 'T恤', type: 'T恤' },
      { label: '外套', type: '外套' },
      { label: '套装', type: '套装' },
      { label: '裙装', type: '裙装' },
      { label: '裤装', type: '裤装' },
      { label: '上衣', type: '上衣' },
      { label: '针织毛衣', type: '针织毛衣' },
      { label: '连衣裙', type: '连衣裙' },
      { label: '牛仔裤', type: '牛仔裤' },
      { label: '更多', type: '' }
    ]);
 
    // 价格格式化函数
    const formatPrice = (price) => {
      if (price === undefined || price === null) return '0.00';
      const numericPrice = typeof price === 'string' ? parseFloat(price) : price;
      if (typeof numericPrice !== 'number' || isNaN(numericPrice)) {
        return '0.00';
      }
      return numericPrice.toFixed(2);
    };
 
    // 计算属性：去重后的搜索结果
    const uniqueSearchResults = computed(() => {
      const seen = new Set();
      return searchResults.value.filter(item => {
        const duplicate = seen.has(item.id);
        seen.add(item.id);
        return !duplicate;
      });
    });
 
    const fetchCartData = () => {
      const userName = sessionStorage.getItem("userName");
      if (!userName) {
        cartItemCount.value = 0;
        return;
      }
 
      axios.get('http://localhost:3001/cartList')
        .then(res => {
          const userCart = res.data.find(cart => cart.userName === userName);
          
          if (userCart && userCart.goodsList) {
            cartItemCount.value = userCart.goodsList.reduce((total, item) => {
              return total + (item.num || 0);
            }, 0);
          } else {
            cartItemCount.value = 0;
          }
        })
        .catch(error => {
          console.error('获取购物车数据失败:', error);
          cartItemCount.value = 0;
        });
    };
 
    const searchProducts = async () => {
      if (searchQuery.value.trim() === '') {
        searchResults.value = [];
        return;
      }
      
      try {
        const response = await axios.get('http://127.0.0.1:3000/api/goods/getAllGoods');
        
        console.log('API 响应:', response.data);
        
        let goodsList = [];
        if (response.data.status === 0 && Array.isArray(response.data.data)) {
          goodsList = response.data.data;
        } else if (Array.isArray(response.data)) {
          goodsList = response.data;
        } else {
          console.error('意外的API响应格式:', response.data);
          searchResults.value = [];
          return;
        }
        
        // 执行模糊搜索并保留原始数据
        const filteredResults = goodsList.filter(item =>
          item.name && item.name.toLowerCase().includes(searchQuery.value.toLowerCase())
        ).slice(0, 10);
        
        searchResults.value = filteredResults;
        showResults.value = true;
        resetAutoHide();
      } catch (error) {
        console.error('搜索失败:', error);
        searchResults.value = [];
      }
    };
 
    const selectNav = (index, type) => {
      activeNavIndex.value = index;
      emit('type-selected', { type });
    };
 
    const goToDetail = (goodsId) => {
      router.push({
        path: '/goodsdetail/goodsintro',
        query: { goodsid: goodsId }
      });
      showResults.value = false;
    };
 
    const highlightItem = (index) => {
      highlightedIndex.value = index;
    };
 
    const hideResults = () => {
      autoHideTimer.value = setTimeout(() => {
        showResults.value = false;
      }, 200);
    };
 
    const pauseAutoHide = () => {
      if (autoHideTimer.value) {
        clearTimeout(autoHideTimer.value);
        autoHideTimer.value = null;
      }
    };
 
    const resumeAutoHide = () => {
      hideResults();
    };
 
    const resetAutoHide = () => {
      pauseAutoHide();
      hideResults();
    };
 
    onMounted(() => {
      // 如果有传入的type，找到对应的索引
      if (props.type) {
        const index = navItems.value.findIndex(item => item.type === props.type);
        if (index !== -1) {
          activeNavIndex.value = index;
        }
      }
      intervalId = setInterval(fetchCartData, 1000);
    });
 
    onUnmounted(() => {
      clearInterval(intervalId);
      if (autoHideTimer.value) {
        clearTimeout(autoHideTimer.value);
      }
    });
 
    return {
      cartItemCount,
      searchQuery,
      searchResults,
      uniqueSearchResults,
      showResults,
      highlightedIndex,
      navItems,
      activeNavIndex,
      searchProducts,
      goToDetail,
      highlightItem,
      hideResults,
      pauseAutoHide,
      resumeAutoHide,
      formatPrice,
      selectNav
    };
  }
};
</script>


<style lang="css" scoped>
/* 确保搜索结果的容器有一个清晰的定位 */
.search-results {
    position: absolute;
    z-index: 100;
    background-color: #f00581;
}

/* 控制搜索结果的列表项样式 */
.search-results ul {
    list-style-type: none;
    /* 去掉默认的列表项符号 */
    padding: 0;
    /* 去掉内边距 */
    margin: 0;
    /* 去掉外边距 */
}

.search-results li {
    padding: 10px;
    /* 给每个列表项一些内边距 */
    border-bottom: 1px solid #eee;
    /* 列表项之间的分隔线 */
}

/* 搜索结果的文本样式 */
.search-results li span {
    /* 这里可以添加控制文本样式的 CSS，比如字体大小、颜色等 */
}


.search-inner {
    margin: 20px;
    overflow: visible;
}

.header .nav a:hover {
    border-bottom: 2px solid #ee006b;
}

/* head-search部分 */
.header .head-search {
    width: 100%;
    height: 120px;
}

.header .head-inner {
    width: 1000px;
    height: 100px;
    padding-top: 20px;
    margin: 0 auto;
}

.header .head-inner .logo {
    width: 140px;
    height: 100px;
    position: relative;
    float: left;
}

.header .head-inner .logo .img-box {
    position: absolute;
    top: 0;
    left: 0px;
    width: 160px;
    height: 100px;
}

.header .head-inner .logo .img-box img {
    width: 150px;
    height: 80px;
}

.head-search .search {
    float: left;
    width: 304px;
    height: 100px;
}

.head-search .service {
    position: relative;
    float: left;
    left:20px;
    width:  27%;
    height: 100%;
}




.head-search .service  span img {
    width:  100%;
    height: 100%;
}


.head-search .shop-box {
    width: 96px;
    height: 32px;
    margin-top: 38px;
    margin-left: 19px;
    float: right;
}

.head-search .shop-box .shop-wrap {
    width: 100px;
    padding-left: 5px;
    padding-right: 33px;
    height: 32px;
    line-height: 32px;
    margin-left: 50px;
    background-color: #f6f7f9;
    position: relative;
    border: 1px solid #ccc;
    border-radius: 2px;
    position: relative;
    

}

.head-search .shop-box .shop-wrap a {
    font-size: 12px;
    color: #333;
    
}

.head-search .shop-box .shop-wrap .gwd {
    width: 10px;
    height: 17px;
    position: absolute;
    top: 5px;
    left: 6px;
}

.head-search .shop-box .shop-wrap img {
    width: 15px;
    height: 17px;
}

.head-search .shop-box .shop-wrap .num {
    position: absolute;
    top: 8px;
    right: 3px;
    width: 24px;
    height: 16px;
    background-color: #f00581;
    border-radius: 8px;
    text-align: center;
    line-height: 16px;
    color: #fff;

}

.head-search .search-inner {
    width: 389px;
    margin-top: 33px;
    float: right;
    position: relative;
}

.head-search .search-inner .input-from {
    width: 420px;
    height: 38px;
    border: 2px solid #fa2a83;
    border-radius: 1px;
}

.head-search .search-inner .input-from input {
    width: 420px;
    height: 34px;
    padding: 2px 12px;
    border: none;
    font-size: 14px;
    line-height: 30px;
    color: #333;
    outline: none;

}

.head-search .search-inner .input-from .button {
    width: 53px;
    height: 38px;
    padding-top: 8px;
    border-radius: 2px;
    text-align: center;
    position: absolute;
    top: 0;
    right: -32px;
    background-color: #fa2a83;
}

.head-search .search-inner .input-from .button span img {
    width: 22px;
    height: 22px;
}

/* mian-nav部分 */
.header .mian-nav {
    width: 100%;
    height: 43px;
}

.header .mian-nav .mian {
    width: 1000px;
    height: 43px;
    margin: 0 auto;
}

.header .mian-nav .mian .sps {
    width: 156px;
    height: 43px;
    float: left;
    background-color: #fa2a83;
    margin-right: 20px;
}

.header .mian-nav .mian .sps a {
    display: inline-block;
    width: 136px;
    line-height: 43px;
    color: #fff;
    font-size: 16px;
    text-align: center;
    padding: 0 10px;
}

.header .mian-nav .mian .sps a img {
    margin-right: 6px;
    margin-top: -3px;
    vertical-align: middle;
}

.header .mian-nav .mian ul li {
    float: left;
    padding: 0 10px;
    text-align: center;
}

.header .mian-nav .mian ul li a {
    line-height: 43px;
    font-size: 16px;
    color: #333;
}

.header .mian-nav .mian ul li a.active {
    color: #f00581;
    font-weight: 700;
}

.header .mian-nav .mian ul li .vipFont {
    display: inline-block;
    width: 5px;
    height: 5px;
    position: relative;
    top: -5px;
    border: 1px solid #333;
    border-top: none;
    border-left: none;
    transform: rotate(45deg);
}
</style>